package org.example.erp.controller;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.erp.domain.*;
import org.example.erp.service.InventoryService;
import org.example.erp.service.ProductBomService;
import org.example.erp.service.UnitsService;
import org.example.erp.service.WarehouseService;
import org.example.erp.service.impl.ProClientOrderItemServiceImpl;
import org.example.erp.service.impl.ProClientOrderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@RequestMapping("/api")
@RestController
public class ProClientOrderController {


    @Autowired
    ProClientOrderServiceImpl proClientOrderService;//客户订单表

    @Autowired
    ProClientOrderItemServiceImpl proClientOrderItemService;//客户订单材料表

    @Autowired
    ProductBomService productBomService;//产品物料Bom组成表

    @Autowired
    UnitsService unitsService;//单位表

    @Autowired
    InventoryService inventoryService;//库存表

    @GetMapping("/customerOrders/find")//查询客户订单
    private DataResult findTableAssociation(
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String clientOrderCode,
            @RequestParam(required = false) String clientName,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startOrderDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endOrderDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDeliveryDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDeliveryDate
    ) {
        LambdaQueryWrapper<ProClientOrder> queryWrapper = new LambdaQueryWrapper<>();
        Page<ProClientOrder> page = new Page<>(currentPage, pageSize);
        // 构建查询条件
        if (StringUtils.isNotBlank(clientOrderCode)) {//客户订单编码
            queryWrapper.like(ProClientOrder::getClientOrderCode, clientOrderCode);
        }

        if (StringUtils.isNotBlank(clientName)) {//客户名称
            queryWrapper.like(ProClientOrder::getClientName, clientName);
        }

        if (startOrderDate != null && endOrderDate != null) {//订货日期
            queryWrapper.between(ProClientOrder::getOrderDate, startOrderDate, endOrderDate);
        } else if (startOrderDate != null) {
            queryWrapper.ge(ProClientOrder::getOrderDate, startOrderDate);//订货开始日期
        } else if (endOrderDate != null) {
            queryWrapper.le(ProClientOrder::getOrderDate, endOrderDate);//订货结束日期
        }

        if (startDeliveryDate != null && endDeliveryDate != null) {//交货日期
            queryWrapper.between(ProClientOrder::getDeliveryDate, startDeliveryDate, endDeliveryDate);
        } else if (startDeliveryDate != null) {//交货开始日期
            queryWrapper.ge(ProClientOrder::getDeliveryDate, startDeliveryDate);
        } else if (endDeliveryDate != null) {//交货结束日期
            queryWrapper.le(ProClientOrder::getDeliveryDate, endDeliveryDate);
        }
        // 添加根据 createTime 倒序排序
        page.setOrders(Collections.singletonList(new OrderItem().setAsc(false).setColumn("create_time")));

        page= proClientOrderService.findTableAssociation(queryWrapper, page);
        return DataResult.success(page);
    }

    @GetMapping("/customerOrders/findMaterial")//查询客户订单需求的物料,所在的仓库，以及库存
    public DataResult findMaterial(String clientOrderCode) {
        // 根据特定的 clientOrderCode 查询对应的物料需求
        List<ProClientOrderItem> materialRequirements = proClientOrderItemService.findMaterialA(clientOrderCode);

        // 如果查询结果为空，可以根据业务逻辑决定是否返回错误或空列表
        if (materialRequirements == null || materialRequirements.isEmpty()) {
            return DataResult.success(Collections.emptyList());
        }

        return DataResult.success(materialRequirements);
    }

    @PostMapping("/customerOrders/insert")//添加客户订单
    public DataResult insert(@RequestBody ProClientOrder proClientOrder) {
        boolean save = proClientOrderService.add(proClientOrder);
        if (save) {
            Integer clientOrderId = proClientOrder.getClientOrderId();
            return DataResult.success(clientOrderId);
        } else {
            return DataResult.error("客户订单添加失败");
        }
    }

    @GetMapping("/customerOrders/findInventoryById")//查询bom材料是否存在库存
    public DataResult findInventoryById(@RequestParam String code){
        List<Inventory> inventoryById = inventoryService.findInventoryById(code);
        return DataResult.success(inventoryById);
    }

    @PostMapping("/customerOrders/insertMaterial")//添加客户订单材料
    public DataResult insertMaterialRequirements(@RequestBody ProClientOrderItem proClientOrderItem) {
        boolean save = proClientOrderItemService.save(proClientOrderItem);
        if (save) {
            return DataResult.success(save ? "成功" : "失败");
        } else {
            return DataResult.error("客户订单材料添加失败");
        }
    }

    @PutMapping("/customerOrders/update")//修改订单(包括订单状态)
    public DataResult update(@RequestBody ProClientOrder proClientOrder){
        boolean b = proClientOrderService.updates(proClientOrder);
        if (b){
            return DataResult.success(b ? "成功" : "失败");
        }else {
            return DataResult.error("客户订单修改失败");
        }
    }

    @PutMapping("/customerOrders/updateQuantity")//修改物料需求数量
    public DataResult updateQuantity(@RequestBody ProClientOrderItem proClientOrderItem){
        boolean b = proClientOrderItemService.updateById(proClientOrderItem);
        if (b){
            return DataResult.success(b ? "成功" : "失败");
        }else {
            return DataResult.error("物料需求数量更新失败");
        }
    }

    @DeleteMapping("/customerOrders/delete")//删除订单
    public DataResult delete(@RequestBody List<Long> ids){
        boolean b = proClientOrderService.removeBatchByIds(ids);
        if (b){
            return DataResult.success(b ? "成功" : "删除");
        }else {
            return DataResult.error("客户订单删除失败");
        }
    }

    @DeleteMapping("/customerOrders/deleteMaterial")//删除订单材料
    public DataResult deleteMaterial(Integer id){
        boolean b = proClientOrderItemService.removeById(id);
        if (b){
            return DataResult.success(b ? "成功" : "删除");
        }else {
            return DataResult.error("客户订单删除失败");
        }
    }
}
